package sg.edu.nus.iss.cats.action;

import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.commons.beanutils.BeanUtils;

import sg.edu.nus.iss.cats.form.*;
import sg.edu.nus.iss.cats.model.*;
import sg.edu.nus.iss.cats.controller.*;
import sg.edu.nus.iss.cats.dataaccess.*;
import sg.edu.nus.iss.cats.exception.*;

public class UserEditAction extends Action {

    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
                         throws DAOException, UserUpdateException {

        System.out.println("UserEditAction");

        String userId = request.getParameter("user_id");
        UserManager userMgr = new UserManager();
        User user = userMgr.findUser(userId);

        UserForm newForm = new UserForm();
        try {
            BeanUtils.copyProperties(newForm, user);
        } catch (Exception e) {
            throw new UserUpdateException(
                "Could not populate the Form Bean: " + e);
        }
        request.setAttribute("userForm", newForm);

        Role[] allRoles = userMgr.findAllRoles();
        request.getSession().setAttribute("allRoles", allRoles);

        System.out.println("UserEditAction successful");
        return mapping.findForward("userEdit");
    }
}